<?php

namespace addons\venue\controller;

use app\admin\model\venue\area\Rule;
use app\admin\model\venue\CouponReceive;
use app\admin\model\venue\venue\Relationship;
use app\common\controller\Api;
use \app\admin\model\venue\Coupon as Cp;
use think\Request;

class Coupon extends Api
{
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['couponList'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    protected $config = "";

    public function __construct(Request $request = null)
    {
        $this->config = get_addon_config("venue");
        parent::__construct($request);
    }
    /*
     * 优惠券列表
     */
    public function couponList(){
        $user_id = $this->auth->id??0;
        $data = Cp::where('state',1)
                ->order("weigh","desc")
                ->field("id,title,image,with_amount,used_amount,quota,start_time,end_time,draw_time,astrict,remarks")
                ->select()
                ->each(function ($item) use($user_id){
                    //查询剩余可领优惠券数量
                    $count = CouponReceive::where("coupon_id",$item->id)->count();
                    $item->quota = bcsub($item->quota,$count);
                    if ($item->quota<0){
                        $item->quota = 0;
                    }
                    //判断当前时间是否在优惠券领取时间区间
                    $item->status = 1;
                    if (CouponReceive::get(["user_id"=>$user_id,"coupon_id"=>$item->id])){
                        $item->status = 0;
                    }
                    $item->image = cdnurl($item->image,true);
                });


        $this->success('返回成功',array_merge($data->toArray()));
    }

    /*
     * 领取优惠券
     */
    public function draw(){
        $user_id = $this->auth->id;
        $id   = $this->request->post('id');     //优惠券id
        if (!$id){
            $this->error("请输入优惠券id");
        }
        $coupon = Cp::get($id);
        //判断是否在优惠券领取时间区间
        $draw = explode(' - ',$coupon->draw_time);
        if (time()>=strtotime($draw[0]) && time()<=strtotime($draw[1])){
            //领取优惠券
            CouponReceive::create([
                "user_id"       =>  $user_id,
                "coupon_id"     =>  $coupon->id,
                "money"         =>  $coupon->used_amount,
                "create_time"   =>  time(),
                "state"         =>  0,
            ]);
            $this->success('领取成功');
        }else{
            $this->error("该优惠券已过可领取时间");
        }

    }

    /*
     * 获取可用优惠券
     */
    public function usable(){
        $user_id = $this->auth->id;
        $post = $this->request->post();     //场地信息
        $areaDetail = $post['areaDetail'];     //场地信息

        //查询优惠券领取记录表
        $data = CouponReceive
            ::with(['coupon'])
            ->where(['coupon_receive.state'=>'0','user_id'=>$user_id])
            ->select();

        $price = 0;
        foreach ($areaDetail as $v){
            if (empty($v)){
                $this->error("请选择时间段");
            }
            $relation = Relationship::get($v['areaId']);
            $rule = $relation["rule_id"];
            $details = Rule::get($rule);
            $count = count($v['times']);
            $price = bcadd($price,bcmul($details['price'],$count,2),2);

        }
        $arr = [];
        foreach ($data as $row) {
            //判断优惠券是否过期，更新优惠券状态
            $coupon = Cp::get($row->coupon_id);
            if (time() > $coupon->end_time){
                $row->state = -1;
                CouponReceive::update(["state"=>-1],["id"=>$row->id]);
            }
            $row->getRelation('coupon')->visible(['title','image','start_time','end_time','with_amount','used_amount','remarks']);
            if ($row->coupon->with_amount <= $price && time() < $coupon->end_time){
                $arr[] = $row;
            }
        }


        $this->success('返回成功',$arr);

    }

    /*
     * 我的优惠券列表
     */
    public function list(){
        $user_id = $this->auth->id;

        //查询优惠券领取记录表
        $data = CouponReceive
            ::with(['coupon'])
            ->where(['user_id'=>$user_id])
            ->select();

        foreach ($data as $row) {
            //判断优惠券是否过期，更新优惠券状态
            $coupon = Cp::get($row->coupon_id);
            if (time() > $coupon->end_time){
                $row->state = -1;
                CouponReceive::update(["state"=>-1],["id"=>$row->id]);
            }
            $row->getRelation('coupon')->visible(['title','image','start_time','end_time','with_amount','used_amount','remarks']);

        }

        $this->success('返回成功',$data);


    }
}
